import { assetManager } from 'cc';
import { _decorator, Component, Node, Label, Material, UITransform, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('LabelBatchOptimizer2D')
export class LabelBatchOptimizer2D extends Component {
    @property({ type: Material })
    unifiedMaterial: Material | null = null;

    onLoad() {
        this.optimizeLabelBatching(); 
    }

    optimizeLabelBatching() {
        const labelComponents: Label[] = [];
        // 递归查找当前节点及其子节点下的所有 Label 组件
        this.findLabelsRecursively(this.node, labelComponents);

        if (this.unifiedMaterial) {
            // 统一所有 Label 组件的材质
            labelComponents.forEach((label) => {
                label.material = this.unifiedMaterial;
            });
        }

        // 对 Label 组件按渲染顺序排序
        labelComponents.sort((a, b) => {
            const aWorldPos = a.node.getWorldPosition();
            const bWorldPos = b.node.getWorldPosition();
            // 先比较节点的渲染层级，层级高的优先渲染
            const aPriority = a.node.getComponent(UITransform)?.priority || 0;
            const bPriority = b.node.getComponent(UITransform)?.priority || 0;
            if (aPriority!== bPriority) {
                return aPriority - bPriority;
            }
            // 若渲染层级相同，再比较 y 坐标，y 坐标大的优先渲染
            return bWorldPos.y - aWorldPos.y;
        });

        // 调整节点的渲染顺序
        labelComponents.forEach((label, index) => {
            const uiTransform = label.node.getComponent(UITransform);
            if (uiTransform) {
                uiTransform.priority = index;
            }
        });
    }

    findLabelsRecursively(node: Node, labelComponents: Label[]) {
        const label = node.getComponent(Label);
        if (label) {
            labelComponents.push(label);
        }
        node.children.forEach((child) => {
            this.findLabelsRecursively(child, labelComponents);
        });
    }
}